<?php

/**
 * This is the model class for table "{{file}}".
 *
 * The followings are the available columns in table '{{file}}':
 * @property integer $id
 * @property string $module
 * @property integer $module_id
 * @property string $name
 * @property string $description
 * @property string $doc_type
 * @property double $size
 * @property integer $total_view
 * @property integer $status_code
 * @property string $create_timezone
 * @property string $create_timestamp
 * @property string $create_datetime
 * @property string $create_date
 * @property string $create_time
 * @property integer $create_by
 * @property string $update_timezone
 * @property string $update_timestamp
 * @property string $update_datetime
 * @property string $update_date
 * @property string $update_time
 * @property integer $update_by
 */
class File extends ActiveRecord {

    public $moduleId_;
    public $module_;
    public $name_;
    public $description_;
            
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return File the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{file}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('module_, moduleId_, description_','filter','filter'=>'trim'),
            array('module_', 'required', 'on'=>'create'),
            array('module_', 'length', 'max'=>45),
            array('moduleId_, size_', 'numerical', 'allowEmpty'=>false, 'integerOnly'=>true, 'on'=>'insert, create'),
            array('description_', 'length', 'max'=>'300'),
            array('file_', 'file', 'types'=>'pdf, rar, doc, docx, wps, torrent, zip, txt, ttf, rtf, pps, ppt, jpeg, jpg, gif, png'),
            array('moduleId_, module_, file_, description_, size_', 'safe', 'on' => 'insert, create, userCreate, userUpdate, adminCreate, adminUpdate'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'creator' => array(self::BELONGS_TO, 'User', 'created_by'),
            'modifier' => array(self::BELONGS_TO, 'User', 'modified_by'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'module_id' => 'Module',
            'module' => 'Module',
            'name' => 'Name',
            'type' => 'Type',
            'size' => 'Size',
            'total_view' => 'Total View',
            'status_code' => 'Status Code',
            'create_time' => 'Created Date',
            'create_by' => 'Created By',
            'update_time' => 'Modified Date',
            'update_by' => 'Modified By',
        );
    }

    public function scopes(){
        $t=$this->getTableAlias(false);
        return array(
            'published'=>array(
                'condition'=>$t.'.status_code = :activeStatus'.$t,
                'params'=>array(
                    ':activeStatus'.$t=>Option::STATUS_ACTIVE,
                ),
            ),
            'accessible'=>array(
                'condition'=>$t.'.status_code <> :deleteStatus'.$t,
                'params'=>array(
                    ':deleteStatus'.$t=>Option::STATUS_DELETED,
                ),
            ),
            'ordered'=>array(
                'order'=>implode(',',array(
                    $t.'.created_date DESC',
                )),
            ),
        );
    }
    
    public function module($module = null) {
        $t = $this->getTableAlias(false);
        $this->getDbCriteria()->mergeWith(array(
            'condition' => $t.'.module = :module'.$t,
            'params' => array(
                ':module'.$t => strtolower($module),
            ),
        ));
        return $this;
    }

    public function moduleId($id = null) {
        $t = $this->getTableAlias(false);
        $this->getDbCriteria()->mergeWith(array(
            'condition' => $t . '.module_id = :moduleId'.$t,
            'params' => array(
                ':moduleId'.$t => (int)$id,
            ),
        ));
        return $this;
    }
    
    protected function beforeSave(){
        if(parent::beforeSave()){
            $this->module_id = $this->moduleId_;
            $this->module = strtolower($this->module_);
            
            if($this->isNewRecord){
                $this->total_view=0;
                $this->setCreateDateTime();
            }else{
                $this->setUpdateDateTime();
            }
            return true;
        }else
            return false;
    }
    
    public function getUploadPath() {
        $uploadPath=Yii::app()->params['mediaPath'];
        $format = 'Y/M/d';
        switch ($this->scenario) {
            case 'insert':
            case 'userCreate':
            case 'userUpdate':
            case 'adminCreate':
            case 'adminUpdate':
                return implode('/', array_filter(array(
                    str_replace(Yii::app()->params['mediaDomain'], Yii::app()->params['relativeMediaPath'], $uploadPath),
                    date($format, time()),
                )));
                break;
            case 'delete':
            case 'userDelete':
            case 'adminDelete':
                return implode('/', array_filter(array(
                    str_replace(Yii::app()->params['mediaDomain'], Yii::app()->params['relativeMediaPath'], $uploadPath),
                    date($format, strtotime($this->created_date)),
                )));
                break;
            
            case 'update':
            default:
                return implode('/', array_filter(array(
                    $uploadPath,
                    date($format, strtotime($this->created_date)),
                )));
                break;
        }//end switch
    }
    
    public function isPathExist($directory) {
        if (!file_exists($directory)) {
            if (@mkdir($directory, 0777, true)) {
                if (!is_writable($directory)) {
                    if (chmod($directory)) {
                        return true;
                    }
                }
            }
        }
    }
    
    public function generateFileName($fileName){
        $tempName = strtolower($fileName);
        $fileName = strtr($tempName, array(
            '.pdf'=>'',
            '.rar'=>'',
            '.doc'=>'',
            '.docx'=>'',
            '.wps'=>'',
            '.torrent'=>'',
            '.zip'=>'',
            '.txt'=>'',
            '.ttf'=>'',
            '.rtf'=>'',
            '.pps'=>'',
            '.ppt'=>'',
            '.jpg'=>'',
            '.jpeg'=>'',
            '.png'=>'',
            '.gif'=>'',
        ));
        $extension = str_replace($fileName, '', $tempName);
        
        return implode('-', array_filter(array(
            $this->urlFormat($fileName),
            time().$extension,
            //strtolower($this->module_),
            //$this->moduleId_,
        )));
    }
    
    public function addRecord(){
        $directory=$this->uploadPath;
        $this->isPathExist($directory);
        foreach($this->file_ as $file){
            if(!$this->uploadFile($directory, $file)) continue;
        }//end foreach
    }
    
    public function uploadFile($directory, &$file){
        $fileName=$this->generateFileName($file->name);
        if($file->saveAs($directory.'/'.$fileName)){
            $model=new $this;
            $model->name=$fileName;
            $model->doc_type=$file->type;
            $model->size=$file->size;
            $model->module_=$this->module_;
            $model->moduleId_=$this->moduleId_;
            $model->status_code=Option::STATUS_ACTIVE;
            if($model->save(false)){
                return true;
            }else{
                $this->addErrors($model->getErrors());
                return false;
            }
        }else 
            return false;
    }
    
    
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('module_id', $this->module_id);
        $criteria->compare('module', $this->module, true);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('type', $this->type, true);
        $criteria->compare('size', $this->size);
        $criteria->compare('total_view', $this->total_view);
        $criteria->compare('status_code', $this->status_code);
        $criteria->compare('create_time', $this->create_time, true);
        $criteria->compare('create_by', $this->create_by);
        $criteria->compare('update_time', $this->update_time, true);
        $criteria->compare('update_by', $this->update_by);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }
    
    public function getFileName(){
        return CHtml::encode($this->name);
    }
    
    public function getFilePath(){
        return implode('/', array_filter(array(
            $this->uploadPath, 
            //rawurlencode($this->fileName),
            )));
    }
    
    public function getFileDescription(){
        return $this->description;
    }
    
    public function getFileType(){
        return CHtml::encode($this->doc_type);
    }
    
    public function getFileSize(){
        return empty($this->size)? 0: (double)$this->size;
    }
    
    public function getTotalView(){
        return empty($this->total_view)? 0: (int)$this->total_view;
    }
    
    public function getRealFile(){
        return implode('/', array_filter(array(
                    $this->uploadPath,
                    rawurlencode($this->fileName),
                )));
    }
    
}